package com.ruoyi.framework.config;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.JhBaseEntity;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public class MyMetaObjectHandler implements MetaObjectHandler {
    private static final Logger log = LoggerFactory.getLogger(MyMetaObjectHandler.class);

    @Override
    public void insertFill(MetaObject metaObject) {
        if (ObjectUtils.isNotEmpty(metaObject) && metaObject.getOriginalObject() instanceof JhBaseEntity) {
            JhBaseEntity baseEntity = (JhBaseEntity) metaObject.getOriginalObject();
            Date current = ObjectUtils.isNotEmpty(baseEntity.getJhCreatedTime())
                    ? baseEntity.getJhCreatedTime() : new Date();
            baseEntity.setJhCreatedTime(current);
            baseEntity.setJhUpdatedTime(current);

            // 尝试获取登录用户名，如果未登录则为null
            String username = getLoginUsername();

            // 仅当已登录且当前字段为空时填充创建人和更新人
            if (StringUtils.isNotBlank(username)) {
                baseEntity.setJhCreatedBy(username);
                baseEntity.setJhUpdatedBy(username);
            } else {
                // 未登录时，将创建人和更新人设置为空
                baseEntity.setJhCreatedBy("-");
                baseEntity.setJhUpdatedBy("-");
            }
            baseEntity.setJhDeleted("0");
            baseEntity.setJhRevision(0);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof JhBaseEntity) {
            JhBaseEntity baseEntity = (JhBaseEntity) metaObject.getOriginalObject();
            Date current = new Date();
            // 更新时间填充(不管为不为空)
            baseEntity.setJhUpdatedTime(current);
            String username = getLoginUsername();
            // 当前已登录 更新人填充(不管为不为空)
            if (StringUtils.isNotBlank(username)) {
                baseEntity.setJhUpdatedBy(username);
            }
        }
    }

    /**
     * 获取登录用户名
     */
    private String getLoginUsername() {
        LoginUser loginUser;
        try {
            loginUser = SecurityUtils.getLoginUser();
        } catch (Exception e) {
            log.warn("自动注入警告 => 用户未登录");
            return null;
        }
        return loginUser.getUsername();
    }


}
